module.exports = app => { 
  const express = require('express')
  //token有关的包
  const jwt = require('jsonwebtoken')
  const Blogs = require('./models/Blogs.js')
  const Admin = require('./models/Admin.js')

  //创建路由实例
  const router = express.Router()

  //定义验证是否登录的中间件
  const auth = async (req, res, next) => {
    //获取前端传过来的token,转为字符串，通过空格截取将Bearer与token分为两节，pop取后一项
    const token = String(req.headers.authorization || '').split(' ').pop()
    if (!token) {
      return res.status(401).send({ message: '请先登录' })
    } 
    const { id } = jwt.verify(token, app.get('key'))
    const user = await Admin.findById(id)
    if (user) {
      await next()
    } else { 
      return res.status(401).send({ message: '请先登录' })
    }
  }

  //添加博客的接口
  router.post('/writing', auth, async (req, res) => { 
    const model = await Blogs.create(req.body)
    res.send(model)
  })
  //展示所有博客接口
  router.get('/read', auth, async (req, res) => { 
    const items = await Blogs.find().limit(50)
    res.send(items)
  })
  //根据id查找相应的数据
  router.get('/read/:id', auth, async (req, res) => { 
    const item = await Blogs.findById(req.params.id)
    res.send(item)
  })
  //删除博客接口
  router.delete('/delete/:id', auth, async (req, res) => { 
    await Blogs.findByIdAndDelete(req.params.id)
    res.send({
      success: true
    })
  })
  //修改博客接口
  router.put('/put/:id', auth, async (req, res) => { 
    const newBlogs = await Blogs.findByIdAndUpdate(req.params.id, req.body)
    res.send(newBlogs)
  })
  //搜索博客接口
  router.get('/search/:text',auth, async (req, res) => {
    const model = await Blogs.find()
    const items = []
    model.map(item => { 
      if (item.title.indexOf(req.params.text) != -1) {
        items.push(item)
      }
    })
    res.send(items)
  })

  //注册接口
  router.post('/register', auth, async (req, res) => {
    const user = await Admin.findOne({ username: req.body.username })
    if (user == null) {
      const newUser = await Admin.create(req.body) 
      res.send({ message: '用户注册成功' })
    } else { 
      res.status(422).send({ message: '用户已存在' })
    }
  })
  //用户列表接口
  router.get('/register', auth, async (req, res) => { 
    const adList = await Admin.find()
    //隐藏一个账号，让前端无法删除
    const newAdList = []
    adList.map(item => { 
      if (item.username !== '1759369735') {
        newAdList.push(item)
      }
    })
    res.send(newAdList)
  })
  //删除用户接口
  router.delete('/del/:id', auth, async (req, res) => { 
    await Admin.findByIdAndDelete(req.params.id)
    res.send({
      success: true
    })
  })
  //登录接口
  router.post('/login', async (req, res) => {
    const { username, password } = req.body
    const user = await Admin.findOne({ username }).select('+password')
    if (user) {
      if (username === user.username && password === user.password) {
        //sign方法生成token，第一个参数为要保存的信息（可以是任意信息），第二个参数秘钥（为app全局注册一个变量用来做秘钥）
        const token = jwt.sign({ id: user.id }, app.get('key'))
        res.send({ token, username })
      } else { 
        res.status(422).send({ message: '用户名或密码错误' })
      }
    } else {
      res.status(402).send({ message: '用户不存在, 请联系管理员' })
    }
  })

  app.use(router)
}